package com.rq.test;

public class BytesHexStrTranslate {
  private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

  private static String bytesToHexString(byte[] src) {
    StringBuilder stringBuilder = new StringBuilder("");
    if (src == null || src.length <= 0) {
      return null;
    }
    for (int i = 0; i < src.length; i++) {
      int v = src[i] & 0xFF;
      String hv = Integer.toHexString(v);
      if (hv.length() < 2) {
        stringBuilder.append(0);
      }
      stringBuilder.append(hv);
    }
    return stringBuilder.toString();
  }

  private static String toStringHex2(byte[] src) {
    String s = bytesToHexString(src);
    byte[] baKeyword = new byte[s.length() / 2];
    for (int i = 0; i < baKeyword.length; i++) {
      try {
        baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    try {
      s = new String(baKeyword, "utf-8");// UTF-16le:Not
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    return s;
  }

  public static String bytesToHexFun1(byte[] bytes) {
    // 一个byte为8位，可用两个十六进制位标识
    char[] buf = new char[bytes.length * 2];
    int a = 0;
    int index = 0;
    for (byte b : bytes) { // 使用除与取余进行转换
      if (b < 0) {
        a = 256 + b;
      } else {
        a = b;
      }

      buf[index++] = HEX_CHAR[a / 16];
      buf[index++] = HEX_CHAR[a % 16];
    }

    return new String(buf);
  }

  public static String bytesToHexFun2(byte[] bytes) {
    char[] buf = new char[bytes.length * 2];
    int index = 0;
    for (byte b : bytes) { // 利用位运算进行转换，可以看作方法一的变种
      buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
      buf[index++] = HEX_CHAR[b & 0xf];
    }

    return new String(buf);
  }

  public static String bytesToShowRes(byte[] bytes) {
    return bytesToHexString(bytes);
    //        bytesToHexFun3(bytes);
  }

  //  二进制字节转十六进制时
  //  将字节高位与0xF0做"&"操作,然后再左移4位，得到字节高位的十六进制A;
  //  将字节低位与0x0F做"&"操作，得到低位的十六进制B
  //  将两个十六进制数拼装到一块AB就是该字节的十六进制表示


  private static String bytesToHexFun3(byte[] bytes) {
    StringBuilder buf = new StringBuilder(bytes.length * 2);
    for (byte b : bytes) { // 使用String的format方法进行转换
      buf.append(String.format("%02x", new Integer(b & 0xff)));
    }
    return buf.toString();
  }

  public static byte[] StringtoBytes(String str) {
    if (str == null || str.trim().equals("")) {
      return new byte[0];
    }

    byte[] bytes = new byte[str.length() / 2];
    for (int i = 0; i < str.length() / 2; i++) {
      String subStr = str.substring(i * 2, i * 2 + 2).toLowerCase();
      bytes[i] = (byte) Integer.parseInt(subStr, 16);
    }
    return bytes;
  }
}
